package yamen.bdwm.data;

import java.util.ArrayList;
import java.util.Collections;

import yamen.bdwm.data.interfaces.onListRefreshedListener;
import yamen.bdwm.datastruct.MoreAdapter;
import yamen.bdwm.datastruct.MoreAdapter.onMoreClicked;
import yamen.bdwm.datastruct.MoreAdapter.onMoreOver;
import yamen.bdwm.datastruct.WmItem;
import yamen.bdwm.datastruct.WmList;
import yamen.bdwm.datastruct.WmMailItem;
import android.os.AsyncTask;

public class MailList extends WmList {
	private int fromid = 0;

	public void getRefreshed(final onListRefreshedListener mListener) {
		fromid=0;
		getRefreshedForNum(mListener);
	}

	void getRefreshedForNum(final onListRefreshedListener mListener) {
		new AsyncTask<Void, Void, Integer>() {

			@Override
			protected Integer doInBackground(Void... params) {
				ArrayList<WmMailItem> wms = null;
				wms = WmMyData.getinstance().parser.getMail(fromid);

				if (wms == null)
					return -1;
				if (fromid == 0)
					MailList.this.list.clear();
				int a = 0;
				Collections.reverse(wms);
				for (WmMailItem i : wms) {
					int mid = Integer.parseInt(i.mid);
					if (fromid == 0 || fromid > mid)
						fromid = mid;
					a += MailList.this.Add((WmItem) i);
				}
				return new Integer(a);
			}

			protected void onPostExecute(Integer i) {
				if(fromid == 1)
					((MoreAdapter)adapterList.get(0)).HideMore();
				else
					((MoreAdapter)adapterList.get(0)).ShowMore();
				if (i >= 0) {
					MailList.this.NotifyAllAdapter();
					if (mListener != null)
						mListener.onRefreshed(i);
				} else {
					if (mListener != null)
						mListener.onError(-1);
				}
			}
		}.execute();
	}

	public void CreateAdapter(int tag, int resource) {
		if (!adapterList.containsKey(tag)) {
			MoreAdapter adapter = new MoreAdapter(resource, this,
					new onMoreClicked() {

						public void Load(final onMoreOver l) {
							getRefreshedForNum(new onListRefreshedListener() {

								public void onRefreshed(int numberOfRefreshed) {
									l.OnMoreOver();
								}

								public void onError(int i) {
									l.OnMoreOver();
								}
							});
						}

						public boolean ShowMore() {
							// TODO Auto-generated method stub
							return true;
						}
					});
			adapterList.put(tag, adapter);
		}
	}
}
